<template>
  <div>
    <!-- Breadcrumb面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 输入框 -->
      <!-- 栅栏布局 -->
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            placeholder="请输入内容"
            v-model="params.query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addUserVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 渲染数据表格 -->
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <!-- 通过作用域插槽 -->
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <!-- 表示这一行的全部数据 -->
            <!-- {{ scope.row }} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 通过作用域插槽渲染作用域列  slot-scope="scope"-->

          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="getUsersEdite(scope.row.id)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-delete"
              size="mini"
              @click="removeUsersInfo(scope.row.id)"
            ></el-button>

            <el-tooltip
              effect="dark"
              content="角色分配"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addUserVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 内容主体区域 -->
        <el-form
          :model="addForm"
          :rules="addRules"
          ref="addFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加编辑用户信息对话框 -->
      <el-dialog
        title="编辑用户信息"
        :visible.sync="usersEditeVisible"
        width="50%"
        @close="editeDialogClose"
      >
        <el-form
          :model="editeForm"
          :rules="editeFormRules"
          ref="editeFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editeForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editeForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editeForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="usersEditeVisible = false">取 消</el-button>
          <el-button type="primary" @click="editeUsersInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRolesDialogVisible"
        width="50%"
        @close="setRolesDialogclosed"
      >
        <div>
          <p>当前的用户：{{ userInfo.username }}</p>
          <p>当前的角色：{{ userInfo.role_name }}</p>
          <p>
            分配新的角色：
            <el-select v-model="checkedRolse" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoles"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };

    // 验证手机的规则
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|18|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    return {
      params: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      // 添加新用户对话框
      addUserVisible: false,
      // 修改用户信息对话框
      usersEditeVisible: false,
      // 控制角色分配框的显示与隐藏
      setRolesDialogVisible: false,
      // 用户信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 选中的角色
      checkedRolse: "",
      // 添加用户绑定的用户信息
      addForm: {
        usersname: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 绑定规则
      addRules: {
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 查询用户基本信息
      editeForm: {},
      // 修改用户信息规则
      editeFormRules: {
        // 邮箱规则
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        // 手机号规则
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    // 获取用户数据列表
    async getUsersList() {
      const { data: res } = await this.$axios.get("users", {
        params: this.params,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户数据列表失败！！！");
      }
      this.total = res.data.total;
      this.userList = res.data.users;
      // console.log(res);
    },

    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.params.pagesize = newSize;
      this.getUsersList();
    },

    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.params.pagenum = newPage;
      this.getUsersList();
    },

    // 保存用户修改状态
    async userStateChange(newState) {
      console.log(newState);
      const { data: res } = await this.$axios.put(
        `users/${newState.id}/state/${newState.mg_state}`
      );
      if (res.meta.status !== 200) {
        res.data.my_state = !newState.my_state;
        this.$message.error("修改用户状态失败");
      }
      this.$message.success("修改用户状态成功");
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      // console.log(this);
      this.$refs.addFormRef.resetFields();
    },

    // 为表单添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$axios.post("users", this.addForm);
        if (res.meta.status !== 201) {
          return this.$message.error("添加用户失败");
        }

        this.$message.success("添加用户成功");
        // 隐藏添加用户框
        this.addUserVisible = false;
        // 刷新数据
        this.getUsersList();
      });
    },

    //编辑用户信息对话框
    async getUsersEdite(id) {
      const { data: res } = await this.$axios.get(`users/` + id);
      this.usersEditeVisible = true;
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户数据失败");
      }
      // this.$message.success('（编辑用户框）获取用户数据成功');
      this.editeForm = res.data;
      // console.log(res.data);
    },

    // 监听关闭编辑用户框事件重置
    editeDialogClose() {
      this.$refs.editeFormRef.resetFields();
    },
    // 发起表单前的预验证
    editeUsersInfo() {
      this.$refs.editeFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("发起表单预验证失败");
        }
        // console.log(valid);
        // 预验证成功，则进行表单数据修改
        const { data: res } = await this.$axios.put(
          `users/` + this.editeForm.id,
          { email: this.editeForm.email, mobile: this.editeForm.mobile }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新数据失败");
        }
        // 更新数据成功
        // 关闭编辑框
        this.usersEditeVisible = false;
        // 重新渲染一下数据
        this.getUsersList();
        this.$message.success("更新数据成功");
      });
    },
    // 删除单个用户信息
    async removeUsersInfo(id) {
      // 弹出提示框，确认是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 如果用户确认删除，则返回字符串confirm
      // 如果用户点击取消，则返回字符串cancle
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // console.log("确认删除了用户");
      // 发送删除请求
      const { data: res } = await this.$axios.delete(`users/` + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      this.$message.success("用户删除成功");
      // 刷新数据
      this.getUsersList();
    },

    // 展示角色
    async setRoles(userInfo) {
      this.userInfo = userInfo;

      //  在设置角色列表之前，需要获取全部角色列表
      const { data: res } = await this.$axios.get("roles");
      if (res.meta.status !== 200) {
        this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data;
      console.log(this.rolesList);
      this.setRolesDialogVisible = true;
    },
    // 保存角色分配
    async saveRoles(){
     const {data:res} =  await this.$axios.put(`users/${this.userInfo.id}/role`,{rid:this.checkedRolse});
     if(res.meta.status!==200){
       return this.$message.error("角色分配失败");
     }
     this.$message.success("角色分配成功");
    //  更新角色列表
    this.getUsersList();
    // 关闭对话框
    this.setRolesDialogVisible = false;
    },

    // 重置分配角色对话框
    setRolesDialogclosed(){
      this.checkedRolse='';
      this.userInfo={};
    }
  },
};
</script>

<style scoped>
</style>